#include "TgBotAPI.h"
#include "tgbot_service.h"
#include "streamdata.h"
#include "8000_tgbot_api.pb.h"

#define MSG_MAX_LENGTH 2048


static std::map<std::string,std::string> http_json_heads = {{"Content-Type","application/json"}};

static bool __init__ = TgBotAPI::Init();

bool TgBotAPI::Init()
{
    // 绑定协议枚举处理函数
    Ctx.msg_router.BindMsg(tgbot::TGBOT_NOTIFY_MESSAGE_REQ, TgBotAPI::HandleNotifyTgGroupMessage);
    // 执行 分钟任务
    Ctx.msg_router.BindTimer(TIMER_MINITE, [](int timer_id)->int{
            TgBotService::Instance()->SendMessageToTgGroup();
            TimerEvent u(timer_id, 1 * 1000);// 每秒调用一次发送
            Ctx.timer_event_activator->signal(u.event);
            return 0;
        });
    
    return true;
}


void TgBotAPI::HandleNotifyTgGroupMessage(MsgData&& msg_data)
{

    tgbot::TgBotNotifyMessageReq req;
    tgbot::TgBotNotifyMessageResp resp;
    
    do
    {
        // 反序列化 服务间消息
        if (!req.ParseFromArray(msg_data.data.data(), msg_data.data.size()))
        {
            resp.set_error_code(tgbot::ErrorCode::Failed);
            log_error("Server Message Parser Failed !!!");
            break;
        }
        log_debug("Server Message Parser Suceess !!! req: %s;", req.ShortDebugString().c_str());

        // 单条消息限制长度，便于查看  超出丢弃打印日志
        if(req.msg_text().size() > MSG_MAX_LENGTH || req.msg_type().size() > MSG_MAX_LENGTH)
        {
            resp.set_error_code(tgbot::ErrorCode::Failed);
            log_error("Server Message Exceed 2048byte Length Limit, msg_type:%s, msg_text:%s;", req.msg_type().c_str(), req.msg_text().c_str());
            break;
        }
        
        // 加入消息队列
        if(!TgBotMgr::Instance()->PushMessageQue(req.msg_type(),req))
        {
            resp.set_error_code(tgbot::ErrorCode::Failed);
            // 日志输出丢弃消息
            log_error("Server Message Add MessageQue Failed, msg_type:%s, msg_text:%s;", req.msg_type().c_str(), req.msg_text().c_str());
            break;
        }

        resp.set_error_code(tgbot::ErrorCode::Success);
    } while(false);

    // 回包
    Ctx.host->MtSendtoOneSrv(tgbot::TGBOT_NOTIFY_MESSAGE_RESP, &resp, msg_data.svtype, msg_data.svid, false, msg_data.uuid);
}

